package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //登录设置汉字乱码
        request.setCharacterEncoding("utf-8");
        //1.获取用户名和密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //2.调用业务层实现登录
        User user = userService.login(username, password);
        //3.如果登录成功，将用户的信息保存在会话域中
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            //判断是否勾选了"记住我"
            String remember = request.getParameter("remember");
            //表示勾选
            if (remember != null) {
                //将用户名和密码写到cookie中
                Cookie cookieUser = new Cookie("user", username);
                //设置过期时间
                cookieUser.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(cookieUser);

                //密码
                Cookie cookiePassword = new Cookie("password", password);
                //设置过期时间
                cookiePassword.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(cookiePassword);
            }

            //查询所有的品牌
            response.sendRedirect("selectAll");
        }
        //4.登录失败，将失败信息放在请求域，转发到登录页面
        else {
            request.setAttribute("msg", "用户名或密码不正确");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
